﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AntiObesity.Base;
using AntiObesity.Base.Managers;

namespace AntiObesity.Services
{
    public partial class IntakeHistory : System.Web.UI.UserControl, ICallbackEventHandler
    {
        public DateTime Date
        {
            get
            {
                if (!String.IsNullOrEmpty(Request["date"]))
                {
                    return Convert.ToDateTime(Request["date"]);
                }
                if (ViewState["date"] != null)
                {
                    return Convert.ToDateTime(ViewState["date"]);
                }
                return DateTime.Today;
            }
            set
            {
                ViewState["date"] = value;
            }
        }

        public bool ShowDateChanger
        {
            get { return dateChanger.Visible; }
            set { dateChanger.Visible = value; }
        }
        public bool HideEmptyTable { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            String callbackScript = "function CallServer(arg, context)" + "{ " + cbReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            Update();
        }

        private string GetUserFriendlyDate()
        {
            var days = DateTime.Today - Date;

            if (days.TotalDays == 0) return "Today";
            if (days.TotalDays == 1) return "Yesterday";
            if (days.TotalDays == -1) return "Tomorrow";
            if (Date.Year == DateTime.Today.Year) return Date.ToString("dd MMMM");
            return Date.ToString("dd MMMM yyyy");
        }

        protected void btnPrev_Click(object sender, ImageClickEventArgs e)
        {
            var date = Date.Yesterday();
            // TODO: this code removes other query strings. Change if necessary
            Response.Redirect(Request.Path + "?date=" + HttpUtility.UrlEncode(date.ToShortDateString()));
        }

        protected void btnNext_Click(object sender, ImageClickEventArgs e)
        {
            var date = Date.Tomorrow();
            // TODO: this code removes other query strings. Change if necessary
            Response.Redirect(Request.Path + "?date=" + HttpUtility.UrlEncode(date.ToShortDateString()));
        }

        public void Update()
        {
            lblDate.Text = GetUserFriendlyDate();

            var intakes = IntakeManager.GetAll(Date, Date.Tomorrow(), Session.GetCurrentUser().ID);
            lstIntakes.DataSource = intakes;
            DataBind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var btn = sender as IButtonControl;
            var id = btn.CommandArgument;
            IntakeManager.Delete(id);
            Update();
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            var btn = sender as IButtonControl;
            var index = Convert.ToInt32(btn.CommandArgument);
            lstIntakes.EditIndex = index;
            lstIntakes.DataBind();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            //lstIntakes.RowEditing += new GridViewEditEventHandler(lstIntakes_RowEditing);
            var btn = sender as IButtonControl;
            //var index = Convert.ToInt32(btn.CommandArgument);
            lstIntakes.EditIndex = -1;
            lstIntakes.DataBind();
        }

        void lstIntakes_RowEditing(object sender, GridViewEditEventArgs e)
        {
            e.Cancel = false;
        }

        public void Update(DateTime dateTime)
        {
            Date = dateTime;
            Update();
        }

        #region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return message;
        }

        string message;

        public void RaiseCallbackEvent(string eventArgument)
        {
            try
            {
                var data = eventArgument.Split('|');
                var intakeID = new Guid(data[0]);
                var value = (float)Convert.ToDouble(data[1]);

                var intake = IntakeManager.FindByID(intakeID);
                intake.Quantity = value;
                IntakeManager.Persist(intake);
                message = "Value changed successfully";
            }
            catch (Exception err)
            {
                message = err.Message;
            }
        }

        #endregion

    }
}